/**    
 * @{#} ShareUtils.java Create on 2014-7-2 上午10:26:21    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.evan.common.share;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.utils.CommonUtility;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class ShareWXUtils {

	private static ShareWXUtils shareUtils;
	private Context context;

	private IWXAPI wxApi;

	public static String APP_ID, APP_SECRET;

	public static void setWXAPPID(String app_id) {
		APP_ID = app_id;
	}

	public static void setWXAPPSECRET(String app_secret) {
		APP_SECRET = app_secret;
	}

	public ShareWXUtils(Context context) {
		this.context = context;
		wxApi = WXAPIFactory.createWXAPI(context, APP_ID, false);
		wxApi.registerApp(APP_ID);
	}

	public static ShareWXUtils getInstance(Context context) {
		if (CommonUtility.isNull(shareUtils)) {
			shareUtils = new ShareWXUtils(context);
		}
		return shareUtils;
	}

	public void share2WXWEB(String url, Object title, Object description,
			boolean isFriend) {
		if (!wxApi.isWXAppInstalled()) {
			CommonUtility.tip(context, R.string.s_weixin_no_installed);
			return;
		}
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = title.toString();
		msg.description = description.toString();
		Bitmap thumb = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
		msg.thumbData = OUtil.bitmap2ByteArray(thumb);
		thumb.recycle();

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage")
		// String.valueOf(System.currentTimeMillis())
		;
		req.message = msg;
		if (!isFriend) {
			req.scene = SendMessageToWX.Req.WXSceneSession;
		} else {
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
		}
		wxApi.sendReq(req);
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}
}
